package com.interview.javabase.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @description: 请一个手写一个自旋锁
 *
 * @author: zhangshuguang@vichain.com
 * @date: 2019/06/14 13:49
 */
public class Demo11 {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public static void main(String[] args) throws InterruptedException {
        Demo11 demo11 = new Demo11();

        new Thread(() -> {
            demo11.myLock();

            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            demo11.myUnLock();
        },"t1").start();

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            demo11.myLock();
            demo11.myUnLock();
        },"t2").start();
    }

    private void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "进来啦！");

        // 自旋
        while (!atomicReference.compareAndSet(null,thread)){
        }

    }

    private void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "Unlock");
        atomicReference.compareAndSet(thread,null);
    }
}
